﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using System.Collections.Generic;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxAssignController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxAssignController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        [User]
        public ActionResult GetInfo()
        {
            var loops = new List<object>();
            var types = typeof(进展反馈周期);
            foreach (int item in Enum.GetValues(types))
            {
                loops.Add(new { Name = Enum.GetName(types, item), Value = item.ToString() });
            }
            return this.ToJson(new
            {
                success = true,
                AssignUnit = WxUser.LogonInfo.UnitName,
                AssignUnitCode = WxUser.LogonInfo.UnitCode,
                AssignTime = DateTime.Now.ToString("yyyy-MM-dd"),
                AssignLimit = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd"),
                loops
            });
        }
        /// <summary>
        /// 只审核报送进展情况
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Check()
        {
            var AssignID = Form.GetInt("AssignID");
            var m = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == AssignID);
            var ret = 0;
            if (m != null)
            {
                if (m.FeedbackLoop != 进展反馈周期.报送进展情况)
                {
                    return this.ToJson(new
                    {
                        success = false,
                        ret,
                        msg = "进展反馈周期有误"
                    });
                }
                string orgProgressInfo = m.ProgressInfo;
                //任务状态 progressStatus = (任务状态)Form.GetInt("Status");
                审核状态 checkStatus = (审核状态)Form.GetInt("CheckStatus");
                string returnReason = Form.GetString("Reason");
                ret = 1;
                if (checkStatus == 审核状态.同意)
                {
                    SuperviseService.UpdateComplete(m.ItemID, m.ItemType);

                    //todo：加入进展反馈表
                    Yqd_PlanProgress model = new Yqd_PlanProgress();
                    model.ItemID = m.ItemID;
                    model.ItemType = m.ItemType;
                    model.AssignID = m.AssignID;
                    model.TaskID = m.TaskID;
                    model.CheckStatus = 审核状态.待审;
                    model.FeedbackTime = DateTime.Now;
                    model.CheckTime = DateTime.Now;
                    model.Instime = DateTime.Now;
                    model.ProgressInfo = m.ProgressInfo;
                    model.ProofMaterial = "[]";
                    model.ExperienceMaterial = "[]";
                    model.ProgressStatus = 任务状态.已完成;
                    model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                    model.UnitCode = WxUser.LogonInfo.UnitCode;
                    model.AuditStatus = 1;
                    ctx.Yqd_PlanProgress.Add(model);

                    //var msg = ddService.Notification(accountId, headtitle, tID, "任务名称: " + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})退回了进展反馈，请重新报送！", pushStep: 推送流程.工作退回);
                    //Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了退回进展反馈通知，返回值：" + msg);
                }
                else
                {
                    m.ProgressInfo = "";
                    m.Material = "[]";
                    ret = ctx.SaveChanges();
                    SuperviseService.UpdateComplete(m.ItemID, m.ItemType, 任务状态.正常推进);
                }
                //{
                //    if (progressStatus != 任务状态.退回)
                //    {
                //        SuperviseService.UpdateComplete(m.ItemID, m.ItemType, progressStatus);
                //    }
                //}

                var IsJb = false;
                if (m.ItemType == 事项类型.专项交办 || m.ItemType == 事项类型.专项督查)
                {
                    IsJb = true;
                }
                TaskLogService.AddLog(IsJb ? m.ItemID : m.TaskID, checkStatus.ToString() + "了进展情况(" + orgProgressInfo + ")" + (!string.IsNullOrEmpty(returnReason) ? "，退回理由：" + returnReason : ""), IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
        /// <summary>
        /// 添加交办事项
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_Assign model)
        {
            var TaskID = Form.GetLong("TaskID");
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;
            var IsJb = false;
            string headtitle = "", text = "";
            string name = "";
            if (SuperviseID > 0)
            {
                var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    var user = ctx.Yqd_User.SingleOrDefault(x => x.EmployeeCode == s.EmployeeCode);
                    headtitle = "领导督导";
                    //var unit = ctx.Yqd_Unit.Where(x => x.UnitCode == model.LeadUnit).FirstOrDefault();
                    text = $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})现予以交办";
                    name = user.Name + "市领导对该任务进行了督导 \n 任务名称: ";
                }
            }
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
                var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == ItemID);
                if (c != null)
                {
                    headtitle = "领导协调";
                    text = "协调内容  " + c.Item;
                }
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
                var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = "精准督查";
                    text = $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})现对该任务督查发现的问题予以交办";
                }
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
                headtitle = "专项交办";

                text = $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})现予以交办";
                IsJb = true;
            }
            switch (ItemType)
            {
                case 事项类型.钉办督导:
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                    if (s != null && s.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.协同管理:
                    var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == CoordinateID);
                    if (r != null && r.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.精准督查:
                    var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == eSuperviseID);
                    if (e != null && e.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.专项交办:
                    var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == sSuperviseID);
                    if (rs != null && (rs.Status == 任务状态.已完成))
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
            }
            model.ItemID = ItemID;
            model.ItemType = ItemType;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_Assign.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                var TaskName = "";
                var tID = TaskID;
                if (ItemType == 事项类型.专项交办)
                {
                    headtitle = "专项交办";
                    tID = 0;
                    var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == TaskID);
                    if (t != null) TaskName = t.Name;
                    TaskID = sSuperviseID;
                }
                else
                {
                    var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
                    if (task != null) TaskName = task.TaskName;
                }
                //关闭通知
                var msg = ddService.Notification(new List<string>(), headtitle, model.TaskID.ToString(), name + TaskName, text + ",请及时办理。", pushStep: 推送流程.交办, unitCode: model.LeadUnit, superId: SuperviseID);

                //var msg = ddService.Notification(model.LeadUnit, headtitle, tID, name + "任务名称:" + TaskName, text + ",请及时办理！");
                Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了" + ItemType + "交办通知，返回值：" + msg);
                TaskLogService.AddLog(IsJb ? ItemID : TaskID, $"填报了{ItemType.ToString()}责任清单和时间清单", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var AssignID = Form.GetInt("AssignID");
            var assign = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == AssignID);
            var ret = ctx.Database.ExecuteSql("delete from Yqd_Assign where AssignID={0};", AssignID);
            if (ret > 0)
            {
                var IsJb = assign.ItemType == 事项类型.专项交办;
                var TaskID = IsJb ? assign.ItemID : assign.TaskID;
                TaskLogService.AddLog(TaskID, "删除了责任清单和时间清单", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult ReportProgress()
        {
            var AssignID = Form.GetInt("AssignID");
            var ProgressInfo = Form.GetString("ProgressInfo");
            var Material = Form.GetString("Material");
            var assign = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == AssignID);
            var ret = ctx.Database.ExecuteSql("update Yqd_Assign set ProgressInfo={1},Material={2},ReportTime=getdate() where AssignID={0};", AssignID, ProgressInfo, Material);
            if (ret > 0)
            {
                var IsJb = assign.ItemType == 事项类型.专项交办;
                var TaskID = IsJb ? assign.ItemID : assign.TaskID;
                TaskLogService.AddLog(TaskID, "报送了进展情况", IsJb);
                //
                //var (TableName, KeyName) = SuperviseService.GetTableName(assign.ItemType);
                //ret = ctx.Database.ExecuteSql("update " + TableName + " set Status={1} where " + KeyName + "={0}", assign.ItemID, (int)任务状态.已完成);
                //if (ret > 0)
                //{
                //    TaskLogService.AddLog(TaskID, "任务已办结", IsJb, false);
                //}
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
